package com.hcc.export.helper.core.task;

import com.hcc.export.helper.core.domain.ExportTask;
import com.hcc.export.helper.core.domain.po.ExportTaskRecord;
import com.hcc.export.helper.core.event.ExportTaskEvent;
import com.hcc.export.helper.core.service.ExportService;
import com.hcc.export.helper.core.utils.ApplicationContextUtils;
import com.hcc.export.helper.core.utils.CollUtils;
import com.hcc.export.helper.core.utils.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 重试导出任务
 */
@Component
public class RetryExportTask {

    @Autowired
    private ExportService exportService;

//    @Autowired
//    private ExportTaskQueue exportTaskQueue;

    @Value("${export.helper.exportCode:}")
    private String exportCode;

    @Scheduled(cron = "0/10 * * * * ? ")
    public void execute() {
        if (StrUtils.isEmpty(exportCode)) {
            return;
        }

        List<String> exportCodes = Arrays.stream(exportCode.split(","))
                .map(String::trim)
                .distinct()
                .collect(Collectors.toList());

        for (String code : exportCodes) {
            List<ExportTaskRecord> exportTaskRecords = exportService.listFailedRecord(code);
            if (CollUtils.isEmpty(exportTaskRecords)) {
                return;
            }
            exportTaskRecords.forEach(r -> {
                ExportTask exportTask = new ExportTask();
                exportTask.setExportCode(r.getExportCode());
                exportTask.setRecordId(r.getId());
                ApplicationContextUtils.pushEvent(new ExportTaskEvent(exportTask));
            });
        }
    }
}
